const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const jsonError = require('koa-json-error')
const session = require('koa-session');


const index = require('./routes/index')

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(jsonError())
//跨域
app.use(async (ctx, next) => {

  ctx.set("Access-Control-Allow-Origin", "*")
  ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
  ctx.set('Access-Control-Allow-Headers', 'x-requested-with, accept, origin, content-type')
  if (ctx.method == 'OPTIONS') {
    ctx.body = '';
    ctx.status = 204;
  } else {
    await next();
  }
  // await next()
})

//设置session
// app.keys = ['some secret hurr'];
// const CONFIG = {
//   key: 'koa:sess',   //cookie key (default is koa:sess)
//   maxAge: 86400000,  // cookie的过期时间 maxAge in ms (default is 1 days)
//   overwrite: true,  //是否可以overwrite    (默认default true)
//   httpOnly: true, //cookie是否只有服务器端可以访问 httpOnly or not (default true)
//   signed: true,   //签名默认true
//   rolling: false,  //在每次请求时强行设置cookie，这将重置cookie过期时间（默认：false）
//   renew: false,  //(boolean) renew session when session is nearly expired,
// };
// app.use(session(CONFIG, app));

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(` ${ctx.method === 'POST' ? JSON.stringify(ctx.request.body) : JSON.stringify(ctx.request.query)} `)
})

// routes
app.use(index.routes(), index.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
